package org.itboys.mobile.service.mysql.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.http.HttpHelper;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.TianJieWalletBlockRecordMapper;
import org.itboys.mobile.dto.TianJieWalletBlockDto;
import org.itboys.mobile.dto.TianJieWalletBlockRecordDto;
import org.itboys.mobile.entity.mongo.TianJieFinanceAccount;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.*;
import org.itboys.mobile.service.mongo.mobile.TianJieMobileAccountService;
import org.itboys.mobile.service.mongo.web.TianJieMemberService;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gexin.rp.sdk.dto.GtReq.InnerFiled.Type.str;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：天街_钱包_区块链_service
 */
@Service
public class TianJieMobileWalletBlockService extends BaseMySqlService<TianJieWalletBlock> {
    public static String bit_url="http://coinworldau.com/ajax/ticker?coin=bit_cny";

    @Autowired
    private TianJieWalletBlockRecordMapper walletRecordMapper;
    @Autowired
    private TianJieMobileWalletService walletService;

    /**
     * 查找用户区块链钱包
     * @param memberId
     * @return
     */
    @Transactional
    public TianJieWalletBlockDto getWallet(Long memberId){
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        TianJieWalletBlock wallet=null;
        List<TianJieWalletBlock> wallets=super.select(param);
        if(ListUtil.isNotNull(wallets)){
            wallet=wallets.get(0);
        }else {
            wallet=new TianJieWalletBlock(memberId);
            super.insert(wallet);
            wallet=super.find(wallet.getId());
        }
        return packageDtoSingle(wallet);
    }

    /**
     * 通过用户寻找区块链钱包
     * @param memberId
     * @return
     */
    @Transactional
    public TianJieWalletBlock findOne(Long memberId){
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        TianJieWalletBlock wallet=null;
        List<TianJieWalletBlock> wallets=super.select(param);
        if(ListUtil.isNotNull(wallets)){
            wallet=wallets.get(0);
        }else {
            wallet=new TianJieWalletBlock(memberId);
            super.insert(wallet);
            wallet=super.find(wallet.getId());
        }
        return wallet;
    }
    /**
     * 获取区块链（钱包）记录
     * @param request
     * @param memberId
     * @param type  1,充值、退出记录，2，交易记录
     * @return
     */
    public List<TianJieWalletBlockRecordDto> getRecord(HttpServletRequest request, Long memberId,Integer type){
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"");
       // param.put("status", SundayCommonConstants.YES);
        List<Integer>  types = new ArrayList<>();
        if(type==1){
            types.add(SundayCommonConstants.block_record_type_in);
            types.add(SundayCommonConstants.block_record_type_quit);

        }else{
            types.add(SundayCommonConstants.block_record_type_sale);
            types.add(SundayCommonConstants.block_record_type_buy);

        }
        param.put("types",types);
        param.put("memberId",memberId);
     //   List<TianJieWalletRecord> records=
        return packageRecordDtoMuilt(walletRecordMapper.select(param));
    }
    /**
     *
     */
    /**
     * 获取实时虚拟货币价格
     * @param memberId 用户ID。默认不适用，可以根据后期因人而调节价格
     * @param type 货币类型。当前默认1
     * @return
     */
    public  BigDecimal getMarketPrice(Long memberId,Integer type){
       // Map<String,Object> param = new HashMap<String,Object>();
        long start =System.currentTimeMillis();
        String result=HttpHelper.doGet(bit_url);
        long end =System.currentTimeMillis();
        long time =(end-start)/1000;
        //{"error_code":0,"msg":"success","data":{"new_price":5.244,"max_price":5.244,"min_price":5.186,"buy_price":5.243,"sell_price":5.244}}
        logger.info("比特币实时价格，请求时间="+time+"秒,结果="+result);
        //JSONObject.pa
        Map result_map = JSON.parseObject(result,Map.class);
        String result_data_str=String.valueOf(result_map.get("data"));
        Map result_data_map = JSON.parseObject(result_data_str,Map.class);
        String new_price =String.valueOf(result_data_map.get("new_price"));
      //  System.out.println("这个是用JSON类,指定解析类型，来解析JSON字符串!!!");



        //Json
        //{"error_code":0,"msg":"success","data":{"new_price":5.246,"max_price":5.246,"min_price":5.189,"buy_price":5.245,"sell_price":5.246}}


        return new BigDecimal(new_price);
    }
    /**
     * 买入
     * @param memberId
     * @param blockNumber
     */
    public void buy(Long memberId, BigDecimal blockNumber){
        //TianJieMember member = me
        TianJieWalletBlock walletBlock =  findOne(memberId);
        BigDecimal marketPrice = getMarketPrice(memberId,1);
        //2017年12月28日，增加判断
        if(marketPrice.compareTo(new BigDecimal("0"))!=1){
            throw new ErrorException("网络延迟，无法获取交易价格，请稍后重试");
        }
        BigDecimal totalAmount = blockNumber.multiply(marketPrice);
        if(totalAmount.compareTo(walletBlock.getAbleAmount())==1){
            throw new ErrorException("区块链可用余额不足；当前可用："+walletBlock.getAbleAmount()+"元"+"，需要金额："+totalAmount+"元，交易数量："+blockNumber+"元，交易单价："+marketPrice+"元");
        }
        generateRecord(walletBlock, memberId,totalAmount,marketPrice,blockNumber, SundayCommonConstants.block_record_type_buy,"区块链-委托买入");

    }

    /**
     * 卖出
     * @param memberId
     * @param blockNumber
     */
    public void sale(Long memberId, BigDecimal blockNumber){
        if(1==1){
            throw new ErrorException("卖出系统更新为自动卖出，请更新版本");
        }
        TianJieWalletBlock walletBlock =  findOne(memberId);
        BigDecimal marketPrice = getMarketPrice(memberId,1);
        BigDecimal totalAmount = blockNumber.multiply(marketPrice);
        if(blockNumber.compareTo(walletBlock.getBlockNumber())==1){
            throw new ErrorException("区块链持币数量不足；当前持币数量："+walletBlock.getBlockNumber());
        }
        generateRecord(walletBlock, memberId,totalAmount,marketPrice,blockNumber, SundayCommonConstants.block_record_type_sale,"区块链-委托卖出");

    }

    /**
     * 退出区块链
     * @param memberId
     */
    public void quit(Long memberId){
        if(1==1){
            throw new ErrorException("功能已经取消，请更新版本");
        }
        TianJieWalletBlock walletBlock =  findOne(memberId);
        //查询用户是否还持有区块链货币
        if(walletBlock.getBlockNumber().compareTo(new BigDecimal("0"))==1){
            throw new ErrorException("退出区块链需要卖出所有持币数量");
        }
        generateRecord(walletBlock, memberId,null,null,null, SundayCommonConstants.block_record_type_quit,"区块链-退出");


    }







    /**
     * 生成区块链钱包记录
     * @param memberId
     * @param totalAmount 交易总价
     * @param amount 交易单价
     * @param blockNumber
     * @param type
     * @param remark
     */
    @Transactional
    public void generateRecord(TianJieWalletBlock walletBlock,Long memberId,BigDecimal totalAmount,BigDecimal amount,BigDecimal blockNumber,Integer type,String remark){

        if(walletBlock==null){
            walletBlock=findOne(memberId);
        }
        //boolean isChangeWallet=true;//是否修改钱包
        BigDecimal negativeOne=new BigDecimal("-1");//-1
        //本次变动钱包本金
        BigDecimal thisBaseAmount =new BigDecimal("0");
        //本次变动钱包可用本金
        BigDecimal thisAbleAmount =new BigDecimal("0");
        //本次变动钱包持币数量
        BigDecimal thisBlockNumber =new BigDecimal("0");

        //消费卡托管（转入），不生成记录。在消费卡的钱包内生成记录。增加
        if(type==SundayCommonConstants.block_record_type_in){
            //传入的金额是负数。
            totalAmount=totalAmount.multiply(negativeOne);
            TianJieWalletBlockRecord blockRecord=
                    new TianJieWalletBlockRecord( memberId,walletBlock.getId(),
                            totalAmount,null,null,  walletBlock.getAbleAmount(),SundayCommonConstants.block_record_type_in, SundayCommonConstants.block_record_status_done, remark);
            walletRecordMapper.insert(blockRecord);
            thisBaseAmount=totalAmount;
            thisAbleAmount=totalAmount;
        //买入。
        }else if(type==SundayCommonConstants.block_record_type_buy){
            TianJieWalletBlockRecord blockRecord=
                    new TianJieWalletBlockRecord( memberId,walletBlock.getId(),
                            totalAmount,amount,blockNumber,  walletBlock.getAbleAmount(),SundayCommonConstants.block_record_type_buy, SundayCommonConstants.block_record_status_doing, remark);
            walletRecordMapper.insert(blockRecord);
            //变更钱包主体
            thisAbleAmount=totalAmount.multiply(negativeOne);
            thisBlockNumber=blockNumber;
        //卖出。
        }else if(type==SundayCommonConstants.block_record_type_sale){
            //2017年12月14日，自动卖出，非手动
           /* TianJieWalletBlockRecord blockRecord=
                    new TianJieWalletBlockRecord( memberId,walletBlock.getId(),
                            totalAmount,amount,blockNumber,  walletBlock.getAbleAmount(),SundayCommonConstants.block_record_type_sale, SundayCommonConstants.block_record_status_doing, remark);
           walletRecordMapper.insert(blockRecord);
            //变更钱包主体
            //thisAbleAmount=totalAmount;
            //2017年12月14日，卖出不增加钱包余额，指扣数量
            thisBlockNumber=blockNumber.multiply(negativeOne);*/

        } //推出区块链。清空区块链账户
         else if(type==SundayCommonConstants.block_record_type_quit){
          /*  //清空区块链账户
            thisBaseAmount=walletBlock.getBaseAmount().multiply(negativeOne);//本金
            logger.info("-区块链本金-"+thisBaseAmount);
            thisAbleAmount=walletBlock.getAbleAmount().multiply(negativeOne);//可用金额
            logger.info("-区块链可用金额-"+thisAbleAmount);
            thisBlockNumber=walletBlock.getBlockNumber().multiply(negativeOne);//区块链数量
            logger.info("-区块链可用持币数量-"+thisBlockNumber);
            //如果区块链中有多余的收益
            if(walletBlock.getAbleAmount().compareTo(walletBlock.getBaseAmount())!=-1){
                totalAmount=walletBlock.getAbleAmount();
                //没有就返还本金
            }else{
                totalAmount=walletBlock.getBaseAmount();
            }
           // totalAmount=walletBlock.getBaseAmount().add(walletBlock.getAbleAmount()).multiply(negativeOne);
            logger.info("-区块链记录本次交易金额-"+totalAmount);
            //生成区块链记录
            TianJieWalletBlockRecord blockRecord=
                    new TianJieWalletBlockRecord( memberId,walletBlock.getId(),
                            totalAmount,amount,blockNumber,  walletBlock.getAbleAmount(),SundayCommonConstants.block_record_type_quit, SundayCommonConstants.block_record_status_doing, remark);
            walletRecordMapper.insert(blockRecord);

            //生成消费卡交易记录
            //1，解冻本金
            walletService.generateRecord(null,memberId, null,SundayCommonConstants.wallet_record_type_quit_baseamount,"退出区块链-返还本金",0l);
            //2，返回收益。当区块链可用金额大于本金时，才会有收益
            if(walletBlock.getAbleAmount().compareTo(walletBlock.getBaseAmount())==1){
                walletService.generateRecord(null,memberId, walletBlock.getAbleAmount().subtract(walletBlock.getBaseAmount()),SundayCommonConstants.wallet_record_type_quit_profit,"退出区块链-生成收益",0l);
            }*/


        }
        walletBlock.setBaseAmount(walletBlock.getBaseAmount().add(thisBaseAmount));
        walletBlock.setAbleAmount(walletBlock.getAbleAmount().add(thisAbleAmount));
        walletBlock.setBlockNumber(walletBlock.getBlockNumber().add(thisBlockNumber));
        super.update(walletBlock);

    }
    /**
     * 组装DTO，
     * @param wallet
     * @return
     */
    public TianJieWalletBlockDto packageDtoSingle(TianJieWalletBlock wallet){
      // BigDecimal currentRevenue = new BigDecimal("0");
        TianJieWalletBlockDto dto = new TianJieWalletBlockDto(wallet.getId(), wallet.getCreateTime(),wallet.getCreateDate(),
                wallet.getBaseAmount(),wallet.getAbleAmount(),wallet.getBlockNumber());
        return dto;

    }

    /**
     * 组装交易记录DTO
     * @return
     */
    public List<TianJieWalletBlockRecordDto> packageRecordDtoMuilt(List<TianJieWalletBlockRecord> records){
        List<TianJieWalletBlockRecordDto> dtos = new ArrayList<>();
        for(TianJieWalletBlockRecord record:records){
            dtos.add(new TianJieWalletBlockRecordDto(record.getId(), record.getCreateTime(),record.getCreateDate(),
                     record.getTotalAmount(),record.getAmount(),record.getBlockNumber(),record.getType(),record.getStatus()));
        }
        return dtos;
    }

}
